//
//  OAuthViewController.swift
//  002-TDD
//
//  Created by 谭淇 on 15/3/2.
//  Copyright (c) 2015年 谭淇. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {

    let WB_AppKey           = "1562433295"
    let WB_AppSecret        = "548a4c4a2329b5a9f2987f84d09fd93d"
    let WB_Redirect_URL     = "http://m.baidu.com"
    let WB_Grant_Type       = "authorization_code"
    
    let WB_API_URL_String   = "https://api.weibo.com"
    
    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadAuthPage();
    }

    // 加载授权界面
    func loadAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_AppKey)&redirect_uri=\(WB_Redirect_URL)"
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    }
}

extension OAuthViewController: UIWebViewDelegate {
    // 页面重定向
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let result = loadWithCode(request.URL!)
        if let code = result.code {
//            println("有code：\(code)")
            
            // 利用code换取accessToken
            let params = ["client_id": WB_AppKey,
            "client_secret": WB_AppSecret,
            "grant_type": WB_Grant_Type,
            "code": code,
            "redirect_uri": WB_Redirect_URL]
            let urlString = "https://api.weibo.com/oauth2/access_token"
            
            let net = NetworkManager.sharedManager
            // 2.008vLssCBRojhB71b0058bd9yDXM8E
            net.requestJSON(.POST, urlString, params) { (result, error) -> () in
                /// 提问：对于accessToken 字典转模型，不需要使用框架！(简单模型，直接KVC)
                let token = AccessToken(dict: result as! NSDictionary)
                AccessToken.saveAccessToken(token)
                println(token.debugDescription)
            }
        }
        
        if !result.isLoad {
//            SVProgressHUD.showInfoWithStatus("页面不加载")
            
            //我们得到token之后，新浪会不断地返回一个页面，然后我们一直都不加载！，死循环!!
            // 所以我们不能直接调用刷新授权页面的方法
            // 需求是：点击取消按钮，再点击授权按钮还是好使的(不刷新页面，不能够实现)
            if (result.isReloadPage) {
                SVProgressHUD.showInfoWithStatus("你真要取消么？", maskType: SVProgressHUDMaskType.Gradient)
                loadAuthPage()
            }
        }
        
        return result.isLoad
    }
    
    ///  根据URL，确定是否加载界面
    ///  :param: url 页面URL
    ///  :returns: 是否加载界面；如果有code返回code、否则返回nil；是否刷新当前页面
    func loadWithCode(url: NSURL) -> (isLoad: Bool, code: String?, isReloadPage: Bool) {
        // 1.将URL转换成字符串
        let urlString = url.absoluteString
        // 2.如果不是微博的api地址，都不加载
        if urlString!.hasPrefix(WB_API_URL_String) {
            return (true, nil, false)
        } else if urlString!.hasPrefix(WB_Redirect_URL) {
            // 带有回调地址的URL只有两个：1.有code的；2.取消按钮
            if let query = url.query {
                if query.hasPrefix("code=") {
                    return (false, (query as NSString).substringFromIndex(("code=" as NSString).length), false)
                } else {
                    return (false, nil, true)
                }
            }
        }
        return (false, nil, false)
    }
}
